package com.ouyunc.db.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.IllegalSQLInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ouyunc.common.utils.SnowflakeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author fangzhenxun
 * @Description   mybatis-plus 分页层，动态注入
 * @Date  2019/11/4 17:07
 **/
@Configuration
public class MybatisPlusConfig {

    Logger log = LoggerFactory.getLogger(MybatisPlusConfig.class);


    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //分页插件,这里设置为mysql
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //版本锁控制
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        //sql 性能规范
//        interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
        //防止全表更新与删除
//        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    @Bean
    public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
        return plusProperties -> plusProperties.getGlobalConfig().setIdentifierGenerator(idGenerator());
    }

    /**
     * 使用雪花id来作为唯一主键
     * @return
     */
    public IdentifierGenerator idGenerator() {
        return entity -> {
            String bizKey = entity.getClass().getName();
            final long id = SnowflakeUtil.nextId();
            log.info("为{}这个实体类生成主键值--->:{}", bizKey, id);
            return id;
        };
    }



}
